package com.wyg.epserviceBase.config;

import com.wyg.epcommonbase.common.ApiResult;
import com.wyg.epcommonbase.common.exception.ExceptionEnum;
import com.wyg.epcommonbase.common.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: WangYongGan
 * @Date: 2021/10/27 16:44
 * @Description: 拦截异常
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlerConfig extends Exception {
    //拦截系统异常
//    @Autowired
//    @Qualifier("errorLogServiceImpl")
//    ErrorLogService errorLogService;

    //自定义异常
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public ApiResult handlerMyException(MyException e) {
        log.error("自定义异常", e);
        log.error(e.getMessage());
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
        return ApiResult.error(333, e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handlerException(Exception e) {
        log.error("系统异常");
        log.error(e.getMessage());
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
//        errorLogService.insert(2, "系统异常", e.getMessage());
        return ApiResult.error(ExceptionEnum.systemError);
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常", e);
        e.printStackTrace();
        log.error(e.getMessage());
        log.error(e.getLocalizedMessage());
        return handleBindingResult(e.getBindingResult());
    }

    private ApiResult handleBindingResult(BindingResult result) {
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            result.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).forEach(list::add);
        }
        if (CollectionUtils.isEmpty(list))
            return ApiResult.error(ExceptionEnum.paramError);
        else return ApiResult.error(ExceptionEnum.paramError.getCode(), list.toString());
    }

}
